package cn.reone.mbt.ui;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.reone.mbt.R;

public class ScanActivity extends AppCompatActivity {

    @BindView(R.id.scan_device_list)
    ListViewCompat scanDeviceList;
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayList<BluetoothDevice> pairedDevices = new ArrayList<>();
    private DeviceAdapter deviceAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        ButterKnife.bind(this);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        deviceAdapter = new DeviceAdapter(pairedDevices, this);
        scanDeviceList.setAdapter(deviceAdapter);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

        scanDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = deviceAdapter.getItem(position);
                try {
                    BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(device.getAddress());
                    Logger.d(remoteDevice.equals(device));
                    Boolean returnValue = false;
                    if (remoteDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                        //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
                        Method createBondMethod =BluetoothDevice.class.getMethod("createBond");
                        Logger.d("BlueToothTestActivity", "开始配对");
                        returnValue = (Boolean) createBondMethod.invoke(remoteDevice);
                    }
                    if(!returnValue){
                        talk("绑定失败"+
                                (device.getBondState()==BluetoothDevice.BOND_BONDED?"设备已绑定"
                                        :" state = " + device.getBondState()));
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Toast
     *
     * @param str
     */
    private void talk(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        Logger.d(str);
    }

    @Override
    protected void onPause() {
        super.onPause();
        boolean success = mBluetoothAdapter.cancelDiscovery();
        talk((success ? "成功结束扫描" : "结束扫描失败") + mBluetoothAdapter.isDiscovering());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    /**
     * 扫描到设备的广播接收器
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Logger.d(action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Logger.d("found device : " + device.getName() + "\naddress : " + device.getAddress());
                deviceAdapter.add(device);
            }
        }
    };

    @OnClick(R.id.scan_agin)
    public void scanAgin() {
        if (mBluetoothAdapter == null) return;
        deviceAdapter.clear();
        Logger.d("isDiscovering : " + mBluetoothAdapter.isDiscovering());
        mBluetoothAdapter.cancelDiscovery();
        talk("开始扫描"+mBluetoothAdapter.startDiscovery());
    }

}
